<template>
  <div>
    <a-modal
      v-model:visible="visible"
      :title="dishesParams.dishId ? '修改菜品信息' : '添加菜品信息'"
      @cancel="visible = false"
      @before-ok="handleBeforeOk"
    >
      <a-form :model="dishesParams" ref="formRef">
        <a-form-item
          field="dishName"
          label="菜品名称"
          :rules="[{ required: true, message: '菜品名称不能为空' }]"
          validate-trigger="blur"
        >
          <a-input
            style="width: 350px"
            v-model="dishesParams.dishName"
            placeholder="请输入菜品名称"
          />
        </a-form-item>

        <a-form-item
          field="dishType"
          label="类型"
          :rules="[{ required: true, message: '类型不能为空' }]"
          validate-trigger="blur"
        >
          <a-select
            v-model="dishesParams.dishType"
            placeholder="请选择类型"
            style="width: 350px"
          >
            <a-option
              v-for="item of dishTypeArr"
              :value="item.value"
              :label="item.label"
            />
          </a-select>
        </a-form-item>

        <a-form-item
          field="allergenInfo"
          label="过敏食物"
          :rules="[{ required: true, message: '过敏食物不能为空' }]"
          validate-trigger="blur"
        >
          <a-input
            style="width: 350px"
            v-model="dishesParams.allergenInfo"
            placeholder="请输入过敏食物"
          />
        </a-form-item>

        <a-form-item
          field="allergenInfo"
          label="菜品图片"
          :rules="[{ required: true, message: '菜品图片不能为空' }]"
          validate-trigger="blur"
        >
          <a-upload
            list-type="picture-card"
            :file-list="fileList"
            image-preview
            :limit="1"
            @before-upload="beforeUpload"
          />
        </a-form-item>

        <a-form-item
          field="calorie"
          label="热量"
          :rules="[{ required: true, message: '报名人数不能为空' }]"
          validate-trigger="blur"
        >
          <a-input-number
            v-model="dishesParams.calorie"
            :style="{ width: '350px' }"
            placeholder="Please Enter"
            class="input-demo"
            :min="10"
            :max="1000"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-card>
      <a-space size="medium">
        
        <a-input-search
          :style="{ width: '280px' }"
          placeholder="请输入菜品信息"
          search-button
          @search="getDishesListByTitle"
          v-model="keyword"
        />
        <a-button @click="openVisible" type="primary">
          <template #icon>
            <icon-plus />
          </template>
          <template #default>添加信息</template>
        </a-button>
        <a-popconfirm content="你确定要删除这些菜品吗?" @ok="batchDelete">
          <a-button type="primary" status="danger">
            <template #icon>
              <icon-delete />
            </template>
            <template #default>批量删除</template>
          </a-button>
        </a-popconfirm>

      </a-space>
    </a-card>
    <a-card>
      <a-table
        :data="dishesInfoArr"
        :bordered="{ cell: true }"
        :pagination="false"
        row-key="dishId"
        :rowSelection="{
          type: 'checkbox',
          showCheckedAll: true,
          onlyCurrent: false,
        }"
        v-model:selectedKeys="selectDishes"
      >
        <template #columns>
          <a-table-column
            title="菜品名称"
            data-index="dishName"
          ></a-table-column>
          <a-table-column title="类型">
            <template #cell="{ record }">
              <a-tag color="gray" v-if="record.dishType === 1">
                <template #icon>
                  <icon-github />
                </template>
                早餐
              </a-tag>
              <a-tag color="gray" v-if="record.dishType === 2">
                <template #icon>
                  <icon-github />
                </template>
                早点
              </a-tag>
              <a-tag color="gray" v-if="record.dishType === 3">
                <template #icon>
                  <icon-github />
                </template>
                午餐
              </a-tag>
              <a-tag color="gray" v-if="record.dishType === 4">
                <template #icon>
                  <icon-github />
                </template>
                下午茶
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column
            title="过敏食物"
            data-index="allergenInfo"
          ></a-table-column>
          <a-table-column title="热量" data-index="calorie"></a-table-column>
          <a-table-column title="创建日期">
            <template #cell="{ record }">
              {{ formattedDate(record.createdAt) }}
            </template>
          </a-table-column>
          <a-table-column title="操作">
            <template #cell="{ record }">
              <a-space>
                <a-button
                  @click="editDishes(record)"
                  type="outline"
                  size="mini"
                >
                  <template #icon>
                    <icon-edit />
                  </template>
                  <template #default>编辑</template>
                </a-button>
                <a-popconfirm
                  @ok="deleteDishes(record.dishId)"
                  content="你确定要删除吗?"
                >
                  <a-button size="mini" status="danger">
                    <template #icon>
                      <icon-delete />
                    </template>
                    <template #default>删除</template>
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
      <a-pagination
        @change="getDishesInfo"
        @page-size-change="pageSizeChange"
        style="margin-top: 15px"
        :total="total"
        show-total
        show-page-size
        :page-size="pageSize"
        :current="pageNo"
      />
    </a-card>
  </div>
</template>

<script setup lang="ts">
import {
  reqDishesInfoList,
  reqDishesByTitle,
  reqDeleteDishes,
  reqBatchDeleteDishesInfo,
  addOrUpdateDishesInfo,
} from '@/api/dishes/index'
import {
  IconDelete,
  IconEdit,
  IconPlus,
  IconGithub,
} from '@arco-design/web-vue/es/icon'
import { onMounted, reactive, ref, nextTick } from 'vue'
import { Message } from '@arco-design/web-vue'
import { reqUploadImage } from '@/api/publicApi'

let dishesInfoArr = ref([])
let total = ref<number>(0)
let pageNo = ref<number>(1)
let pageSize = ref<number>(10)
let keyword = ref<String>()
let selectDishes = ref([])
let formRef = ref()
let dateRange = ref()

const visible = ref(false)

const fileList = ref([])

const dishTypeArr = [
  {
    value: 1,
    label: '早餐',
  },
  {
    value: 2,
    label: '早點',
  },
  {
    value: 3,
    label: '午餐',
  },
  {
    value: 4,
    label: '下午茶',
  },
]
const dishesParams = reactive({
  dishId: 0,
  dishName: '',
  dishType: '',
  dishImg: '',
  allergenInfo: '',
  calorie: 0,
  createdAt: '',
})
onMounted(() => {
  getDishesInfo()
})

// 文件上传成功的回调
const beforeUpload = async (file: File) => {
  const forms = new FormData()
  forms.append('image', file) // 获取上传图片信息
  let result = await reqUploadImage(forms) //上传图片至和后台文件中
  let obj = {
    url: getImageUrl(result), //格式化图片路径
  }
  fileList.value.push(obj) //将图片路径添加到fileList中
}

// 格式化图片路径
const getImageUrl = (imageUrl: any) => {
  if (imageUrl) {
    // 拼接后端服务器地址和图片地址
    return `http://localhost:8081${imageUrl}`
  }
}

// 获取用户数据
const getDishesInfo = async (pager = 1) => {
  // 收集当前的页码
  pageNo.value = pager
  let result: any = await reqDishesInfoList(pageNo.value, pageSize.value)

  if (result.status === 'OK') {
    dishesInfoArr.value = result.data.records
    total.value = result.data.total
  }
}
// 页码改变
const pageSizeChange = (value: number) => {
  pageSize.value = value
  getDishesInfo(pageNo.value)
}

// 通过标题搜索
const getDishesListByTitle = async () => {
  if (keyword.value) {
    let result: any = await reqDishesByTitle(
      pageNo.value,
      pageSize.value,
      keyword.value,
    )
    if (result.status === 'OK') {
      dishesInfoArr.value = result.data.records
    }
  } else {
    getDishesInfo()
  }
}

// 模态框点击确定
const handleBeforeOk = () => {
  formRef.value.validate(async (r: any, _Record: any) => {
    if (r === undefined) {
      dishesParams.dishImg = fileList.value[0].url

      // 发送请求
      let result = await addOrUpdateDishesInfo(dishesParams)
      if (result.status === 'OK') {
        Message.success(result.message)
        getDishesInfo()
        visible.value = false
      } else {
        Message.error(result.message)
      }
    }
  })
}

// 打开模态框
const openVisible = () => {
  Object.assign(dishesParams, {
    dishId: 0,
    dishName: '',
    dishType: '',
    allergenInfo: '',
    calorie: 0,
    createdAt: '',
  })
  dateRange.value = ['', '']
  fileList.value = []

  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate()
  })
  visible.value = true
}

const editDishes = (_record: any) => {
  fileList.value = []
  Object.assign(dishesParams, _record)
  if (_record.dishImg !== '') {
    fileList.value[0] = {
      url: _record.dishImg,
    }
  }
  visible.value = true
}
const deleteDishes = async (record: any) => {
  let result: any = await reqDeleteDishes(record)
  if (result.status === 'OK') {
    Message.success(result.message)
    getDishesInfo(
      dishesInfoArr.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  }
}

// 批量删除
const batchDelete = async () => {
  if (selectDishes.value.length < 1) {
    Notification.warning({
      title: '删除提示',
      content: '请选择你要删除的用户!',
    })
    return
  }

  let result = await reqBatchDeleteDishesInfo(selectDishes.value)
  if (result.status === 'OK') {
    Message.success(result.message)
    getDishesInfo(pageNo.value)
  }
}

// 格式化时间戳
const formattedDate = (dateParts: any) => {
  let date = new Date(
    dateParts[0],
    dateParts[1] - 1,
    dateParts[2],
    dateParts[3],
    dateParts[4],
    dateParts[5],
  )
  // 转换为格式化的日期字符串
  let year = date.getFullYear()
  let month = ('0' + (date.getMonth() + 1)).slice(-2)
  let day = ('0' + date.getDate()).slice(-2)
  let hours = ('0' + date.getHours()).slice(-2)
  let minutes = ('0' + date.getMinutes()).slice(-2)
  let seconds = ('0' + date.getSeconds()).slice(-2)

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
</script>

<style lang="scss" scoped></style>
